package com.kefu.client.controller;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import com.alibaba.fastjson.JSONObject;

@Controller
@Scope("prototype")
@RequestMapping("/upload")
public class Upload {
	/**
	 * 返回数据格式仅用于layim
	 * @param request
	 * @param response
	 */
	@RequestMapping("/img.c")
	public void img(HttpServletRequest request,HttpServletResponse response) {
		
		// 创建一个通用的多部分解析器
		CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(
				request.getSession().getServletContext());
		// 判断 request 是否有文件上传,即多部分请求

		if (multipartResolver.isMultipart(request)) {
			// 转换成多部分request

			MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
			// 取得request中的所有文件名

			Iterator<String> iter = multiRequest.getFileNames();
			while (iter.hasNext()) {
				// 取得上传文件

				MultipartFile file = multiRequest.getFile(iter.next());
				if (file != null) {
					// 取得当前上传文件的文件名称

					String myFileName = file.getOriginalFilename();
					// 如果名称不为“”,说明该文件存在，否则说明该文件不存在

					if (myFileName.trim() != "") {
						String path = request.getSession().getServletContext().getRealPath("/");

						if (!new File(path + "/imgs").exists()) {
							new File(path + "/imgs").mkdir();
						}
						System.out.println("文件目录存在:" + new File(path + "/imgs/").exists());
						String fn = path + "/imgs/" + "img_" + System.currentTimeMillis() + "_" + myFileName;
						File f = new File(fn);
						try {
							System.out.println("文件存在:" + f.exists());
							if (!f.exists() && f.createNewFile()) {
								file.transferTo(f);
								String fName=request.getContextPath() + "/imgs/" + f.getName();
								responseUpdateImgResultToLayim(response,0,fName,null);
								return;
							} else {
								throw new IOException("创建文件失败");
							}
						} catch (IOException e) {
							e.printStackTrace();
							responseUpdateImgResultToLayim(response,1,null,"创建文件失败");
						}
					}
				}
			}
		}
	}
	@RequestMapping("/file.c")
	public void file(HttpServletRequest request,HttpServletResponse response) {
		
		// 创建一个通用的多部分解析器
		CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(
				request.getSession().getServletContext());
		// 判断 request 是否有文件上传,即多部分请求

		if (multipartResolver.isMultipart(request)) {
			// 转换成多部分request

			MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
			// 取得request中的所有文件名

			Iterator<String> iter = multiRequest.getFileNames();
			while (iter.hasNext()) {
				// 取得上传文件

				MultipartFile file = multiRequest.getFile(iter.next());
				if (file != null) {
					// 取得当前上传文件的文件名称

					String myFileName = file.getOriginalFilename();
					// 如果名称不为“”,说明该文件存在，否则说明该文件不存在

					if (myFileName.trim() != "") {
						String path = request.getSession().getServletContext().getRealPath("/");

						if (!new File(path + "/files").exists()) {
							new File(path + "/files").mkdir();
						}
						System.out.println("文件目录存在:" + new File(path + "/files/").exists());
						String fn = path + "/files/" + "file_" + System.currentTimeMillis() + "_" + myFileName;
						File f = new File(fn);
						try {
							System.out.println("文件存在:" + f.exists());
							if (!f.exists() && f.createNewFile()) {
								file.transferTo(f);
								String fName=request.getContextPath() + "/files/" + f.getName();
								responseUpdateImgResultToLayim(response,0,fName,null);
								return;
							} else {
								throw new IOException("创建文件失败");
							}
						} catch (IOException e) {
							e.printStackTrace();
							responseUpdateImgResultToLayim(response,1,null,"创建文件失败");
						}
					}
				}
			}
		}
	}
	public void responseUpdateImgResultToLayim(HttpServletResponse response,Integer code,String src,String msg){
		Map<String, Object> map = new HashMap<>();
		map.put("code", code);
		if(code!=0){
			map.put("msg",msg);
		}else{
			Map<String,Object> data=new HashMap<String, Object>();
			data.put("src",src);
			map.put("data",data);
		}
		
		String result_json=JSONObject.toJSONString(map);
		//设置响应
		response.setCharacterEncoding("UTF-8");    
		response.setContentType("application/json; charset=utf-8");  
		//返回用户对象
		PrintWriter pw;
		try {
			pw = response.getWriter();
			pw.write(result_json);
			pw.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
